package com.lili.uitl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

public class OssUtil {
    protected static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
    private static final String endpoint = "oss-cn-chengdu-internal.aliyuncs.com";
    private static final String accessKeyId = "LTAI4FtXLhWtC5wk4tTWJ3q2";
    private static final String accessKeySecret = "LwSY59Uhj9shoHP2J8mRVSfNMZ4jeR";
    private static final String bucketName = "oss-xas-1";

    public static String ossUpFile(InputStream inputStream, String name) {
        try {
            // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
            // 创建OSSClient实例。
            String fileName = createFileName().concat(name.substring(name.indexOf(".")));
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, "admin/".concat(fileName), inputStream);
            ossClient.shutdown();
            // 关闭OSSClient。
//            InputStream inputStream = new FileInputStream("<yourlocalFile>");
            StringBuilder stringBuilder = new StringBuilder("http://img.xiaoans.com/");
            stringBuilder.append("admin/").append(fileName);
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String createFileName() {
        Random rand = new Random();
        String formatDate = dateFormatter.format(LocalDateTime.now());
        StringBuilder fileName = new StringBuilder(formatDate);
        for (int i = 0; i < 5; i++) {
            fileName.append((char) (rand.nextInt(26) + 'A'));
        }
        return fileName.toString();
    }


    public static void main(String[] args) throws FileNotFoundException {

        InputStream inputStream = new FileInputStream("H:\\张玲\\IMG_5241.JPG");
        String s = ossUpFile(inputStream, "IMG_5241.JPG");
        System.out.println(s);

    }
}
